package com.dwjm.shop.utils.Merchant;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@WebServlet("/addGoods")
@MultipartConfig
public class GoodsHandler extends HttpServlet {
    private static final String UPLOAD_DIRECTORY = "web/images/goods";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        String title = request.getParameter("title");
        String priceStr = request.getParameter("price");
        String descr = request.getParameter("descr");
        
        // 处理文件上传
        Part filePart = request.getPart("file");
        String fileName = null;
        
        if (filePart != null && filePart.getSize() > 0) {
            // 生成唯一文件名
            fileName = UUID.randomUUID().toString() + getFileExtension(filePart);
            
            // 确保上传目录存在
            Path uploadPath = Paths.get(getServletContext().getRealPath("") + "/" + UPLOAD_DIRECTORY);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 保存文件
            filePart.write(uploadPath.toString() + "/" + fileName);
        }
        
        try {
            // 创建商品对象
            Goods goods = new Goods(
                null, 
                title, 
                new BigDecimal(priceStr), 
                descr, 
                fileName == null ? "" : UPLOAD_DIRECTORY + "/" + fileName,
                "1" // 默认状态为1，表示正常
            );
            
            // 保存到数据库
            MerchantDaoImpl merchantDao = new MerchantDaoImpl();
            int result = merchantDao.addGoods(goods);
            
            // 返回结果
            if (result > 0) {
                response.getWriter().write("Y");
            } else {
                response.getWriter().write("N");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("N");
        }
    }
    
    // 获取文件扩展名
    private String getFileExtension(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] elements = contentDisposition.split(";");
        for (String element : elements) {
            if (element.trim().startsWith("filename")) {
                String fileName = element.substring(element.indexOf("=") + 1).trim().replace("\"", "");
                int lastDot = fileName.lastIndexOf(".");
                if (lastDot > 0) {
                    return fileName.substring(lastDot);
                }
            }
        }
        return ".jpg"; // 默认扩展名
    }
} 